package com.zpp.gobang.controller;

import com.zpp.gobang.model.User;
import com.zpp.gobang.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Object login(String username, String password, HttpServletRequest request){
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)){
            return new User();
        }

        User user = userService.queryByUsername(username);
        if(user == null || !user.getPassword().equals(password)){ //用户不存在或者密码不正确
            return new User();
        }

        //true表示如果存在session则不创建，不存在则创建
        HttpSession session = request.getSession(true);
        user.setPassword(""); //清空密码再返回
        session.setAttribute("user",user);

        return user;
    }

    @PostMapping("/register")
    public Object register(String username, String password){
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)){
            return new User();
        }

        User user = new User();
        try {
            user.setUsername(username);
            user.setPassword(password);
            userService.registerUser(user);
            return user;
        }catch (org.springframework.dao.DuplicateKeyException e){
            return new User();   //用户名重复，注册失败
        }
    }

    @RequestMapping("/getUserInfo")
    public Object getUserInfo(HttpServletRequest request){

        try {
            HttpSession session = request.getSession();
            User user = (User)session.getAttribute("user");
            User newUser = userService.queryByUsername(user.getUsername());  //重新从数据库中获取最新数据
            return newUser;
        }catch (NullPointerException e){  //session为空
            return new User();
        }
    }
}
